package com.jm.call;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;

import java.io.IOException;

/**
 * Created by Administrator on 2017/8/28.
 */

public class SoundManage {
    private MediaPlayer mp;
    private static SoundManage soundManage;
    private int mPlayCount;

    //获取声音文件
    private static AssetFileDescriptor getAssetsFile(Context context, String filename){
        AssetFileDescriptor assetFileDescriptor = null;

        try {
            assetFileDescriptor = context.getResources().getAssets().openFd(filename);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(assetFileDescriptor!=null){
            return assetFileDescriptor;
        }else{
            return null;
        }

    }

    public static synchronized SoundManage getInstance(){
        if(soundManage==null){
            soundManage = new SoundManage();
        }
        return soundManage;
    }
    //播放声音
    public synchronized void playSound(final Context context, final String filename){
        new Thread(){
            @Override
            public void run() {
                super.run();
                AssetFileDescriptor file = getAssetsFile(context,filename);
                if(file==null){
                    return;
                }
                mp = new MediaPlayer();
                mp.reset();
                try {
                    mp.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
                    file.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    mp.release();
                    return;
                }

                try {
                    mp.prepare();
                }catch(Exception e) {
                    e.printStackTrace();
                    mp.release();
                    return;
                }
                mp.start();

                mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        if(mPlayCount==1){
                            mp.release();
                        }else{
                            mp.start();
                        }
                    }
                });
                mp.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                    @Override
                    public void onSeekComplete(MediaPlayer mp) {
                        mp.release();
                    }
                });
            }
        }.start();
    }

    public void stop(){
        try {
            if(mp!=null){
                mp.stop();
            }
        }catch (Exception e){}

    }
}
